﻿using AutoMapper;
//using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
//using Scheduler.Common;
using Scheduler.IServices;
using Scheduler.Model;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Scheduler.Services
{
    public class SysUserInfoServices
    {
        //private readonly SchedulerContext dbContext;
        //private readonly PermissionRequirement _requirement;
        //private readonly IRoleModulePermissionServices _roleModulePermissionServices;
        //private readonly IMapper _mapper;
        //private readonly ILogger<SysUserInfoServices> _logger;

        //public SysUserInfoServices(SchedulerContext schedulerContext, PermissionRequirement permissionRequirement,
        //    IRoleModulePermissionServices roleModulePermissionServices, IMapper mapper, ILogger<SysUserInfoServices> logger)
        //{
        //    dbContext=schedulerContext;
        //    _requirement=permissionRequirement;
        //    _roleModulePermissionServices = roleModulePermissionServices;
        //    _mapper = mapper;
        //    _logger = logger;
        //}
        //public async Task<SysUserInfo> QueryById(long id)
        //{
        //    var user = await dbContext.Users.FindAsync(id);
        //    return user;
        //}
        ///// <summary>
        ///// 登录
        ///// </summary>
        ///// <param name="name">用户名</param>
        ///// <param name="password">密码</param>
        ///// <returns></returns>
        //public async Task<MessageModel<TokenInfoViewModel>> Login(string name, string password)
        //{
        //    string jwtStr = string.Empty;
        //    if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password))
        //    {
        //        return MessageModel<TokenInfoViewModel>.FailResult("用户名或密码不能为空");
        //    }
        //    var user = await dbContext.Users.Where(d => d.LoginName== name && d.LoginPWD==MD5Helper.MD5Encrypt32(password)  && d.IsDeleted == false).ToListAsync();
        //    if (user == null || user.Count == 0)
        //    {
        //        return MessageModel<TokenInfoViewModel>.FailResult("用户名或密码错误");
        //    }
        //    if (user.Count > 0)
        //    {
        //        var userRoles = await GetUserRoleNameStr(name, password);
        //        //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
        //        var claims = new List<Claim>
        //        {
        //            new Claim(ClaimTypes.Name, user.FirstOrDefault().RealName),
        //            new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().Id.ToString()),
        //            new Claim(JwtRegisteredClaimNames.Iat, DateTime.Now.DateToTimeStamp()),
        //            new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
        //        };
        //        claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
        //        var data = await _roleModulePermissionServices.LoginRoleModuleMaps();
        //        var list = (from item in data
        //                    select new PermissionItem
        //                    {
        //                        Url = item.Url,
        //                        Role = item.Role,
        //                    }).ToList();

        //        _requirement.Permissions = list;
        //        var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
        //        return MessageModel<TokenInfoViewModel>.SuccessResult("登录成功", token);
        //    }
        //    else
        //    {
        //        return MessageModel<TokenInfoViewModel>.FailResult("认证失败"); ;
        //    }
        //}
        ///// <summary>
        ///// 获取角色
        ///// </summary>
        ///// <param name="loginName"></param>
        ///// <param name="loginPwd"></param>
        ///// <returns></returns>
        //private async Task<string> GetUserRoleNameStr(string loginName, string loginPwd)
        //{
        //    string roleName = "";
        //    var user = await dbContext.Users.FirstOrDefaultAsync(a => a.LoginName == loginName);
        //    var roleList = await dbContext.Roles.Where(a => a.IsDeleted == false).ToListAsync();
        //    if (user != null)
        //    {
        //        var userRoles = await dbContext.UserRoles.Where(ur => ur.UserId == user.Id).ToListAsync();
        //        if (userRoles.Count > 0)
        //        {
        //            var arr = userRoles.Select(ur => ur.RoleId.ObjToString()).ToList();
        //            var roles = roleList.Where(d => arr.Contains(d.Id.ObjToString()));
        //            roleName = string.Join(',', roles.Select(r => r.Name).ToArray());
        //        }
        //    }
        //    return roleName;
        //}
        ///// <summary>
        ///// 添加用户
        ///// </summary>
        ///// <param name="sysUserInfo">用户基本信息</param>
        ///// <returns></returns>
        //public async Task<string> AddUser(SysUserInfo sysUserInfo)
        //{
        //    string result = "";
        //    var users = await dbContext.Users.Where(d => d.LoginName == sysUserInfo.LoginName && d.IsDeleted == false).ToListAsync();
        //    if (users.Count > 0)
        //    {
        //        result="登录名已存在";
        //    }
        //    sysUserInfo.LoginPWD = MD5Helper.MD5Encrypt32(sysUserInfo?.LoginPWD);
        //    sysUserInfo.Id=Guid.NewGuid().ObjToLong();
        //    await dbContext.Users.AddAsync(sysUserInfo);
        //    var id = await dbContext.SaveChangesAsync();
        //    if (id == 0)
        //    {
        //        result="添加失败";
        //    }
        //    return result;
        //}
        ///// <summary>
        ///// 更新用户
        ///// </summary>
        ///// <param name="sysUserInfo"></param>
        ///// <returns></returns>
        //public async Task<string> UpdateUser(SysUserInfoDto sysUserInfo)
        //{
        //    using var transaction = await dbContext.Database.BeginTransactionAsync();            // 这里使用事务处理
        //    // 1. 验证用户是否存在
        //    var oldUser = await dbContext.Users.FirstOrDefaultAsync(u => u.Id == sysUserInfo.Id && !u.IsDeleted);
        //    if (oldUser is not { Id: > 0 })
        //    {
        //        return "用户不存在或已被删除";
        //    }
        //    if (sysUserInfo.LoginName != oldUser.LoginName)
        //    {
        //        var exists = await dbContext.Users.AnyAsync(u => u.LoginName == sysUserInfo.LoginName && !u.IsDeleted);
        //        if (exists)
        //        {
        //            return "登录名已存在";
        //        }
        //    }
        //    try
        //    {
        //        if (sysUserInfo.LoginPWD != oldUser.LoginPWD)
        //        {
        //            oldUser.CriticalModifyTime = DateTime.Now;
        //        }
        //        _mapper.Map(sysUserInfo, oldUser);
        //        // 无论 Update Or Add , 先删除当前用户的全部 U_R 关系
        //        var usreroles = await dbContext.UserRoles.Where(d => d.UserId == oldUser.Id).ToListAsync();
        //        if (usreroles.Count > 0)
        //        {
        //            var isAllDeleted = await dbContext.UserRoles.Where(ur => ur.UserId == oldUser.Id).ExecuteDeleteAsync();
        //            if (isAllDeleted==0)
        //            {
        //                return "服务器更新异常";
        //            }
        //        }
        //        // 然后再执行添加操作
        //        if (sysUserInfo.RIDs.Count > 0)
        //        {
        //            var userRolsAdd = new List<UserRole>();
        //            sysUserInfo.RIDs.ForEach(rid => { userRolsAdd.Add(new UserRole(oldUser.Id, rid)); });
        //            var oldRole = usreroles.Select(s => s.RoleId).OrderBy(i => i).ToArray();
        //            var newRole = userRolsAdd.Select(s => s.RoleId).OrderBy(i => i).ToArray();
        //            if (!oldRole.SequenceEqual(newRole))
        //            {
        //                oldUser.CriticalModifyTime = DateTime.Now;
        //            }
        //            await dbContext.UserRoles.AddRangeAsync(userRolsAdd);
        //        }
        //        oldUser.LoginPWD = MD5Helper.MD5Encrypt32(oldUser.LoginPWD);
        //        var success = await dbContext.SaveChangesAsync();
        //        await transaction.CommitAsync();
        //        if (success>0)
        //        {
        //            return string.Empty;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        await transaction.RollbackAsync();
        //        _logger.LogError(e, e.Message);
        //        return "更新失败";
        //    }
        //    return string.Empty;
        //}
        ///// <summary>
        ///// 删除用户
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpDelete]
        //public async Task<string> DeleteUser(long id)
        //{
        //    var userInfo = await dbContext.Users.FindAsync(id);
        //    if (userInfo is not null)
        //    {
        //        userInfo.IsDeleted = true;
        //        var success = await dbContext.SaveChangesAsync(); ;
        //        return success>0 ? "删除成功" : "删除失败";
        //    }
        //    else
        //    {
        //        return "删除失败,请传入正确的Id";
        //    }
        //}
    }
}
